<template>
  <div class="digital-signature">
    <div class="signature-card">
      <div class="card-header">
        <h3>{{ title || '电子签名' }}</h3>
        <el-button link icon="el-icon-refresh-right" @click="clearSignature">清除</el-button>
      </div>
      
      <div class="signature-container">
        <canvas
          ref="signatureCanvas"
          :width="canvasWidth"
          :height="canvasHeight"
          class="signature-canvas"
          @mousedown="startDrawing"
          @mousemove="draw"
          @mouseup="endDrawing"
          @mouseleave="endDrawing"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd">
        </canvas>
        <p class="signature-tip">请在上方空白处签名</p>
      </div>
      
      <div class="signature-info" v-if="signatorInfo">
        <p>签名人: {{ signatorInfo.name }}</p>
        <p>职位: {{ signatorInfo.position }}</p>
      </div>
      
      <div class="signature-actions">
        <el-button type="primary" size="small" @click="saveSignature" :disabled="!hasSignature">保存签名</el-button>
        <el-button size="small" @click="previewSignature" :disabled="!hasSignature">预览</el-button>
      </div>
    </div>
    
    <el-dialog title="签名预览" :visible.sync="previewVisible" width="30%">
      <div class="preview-content">
        <img :src="signatureImage" alt="签名预览" class="preview-image" v-if="signatureImage">
        <p v-else class="no-signature">暂无签名</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadSignature" :disabled="!signatureImage">下载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addDigitalSignature, saveSignatory, getSignatoryDetail } from '@/api/qep/certificate/manage'

export default {
  name: 'DigitalSignature',
  props: {
    signatoryId: {
      type: [Number, String],
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    canvasWidth: {
      type: Number,
      default: 400
    },
    canvasHeight: {
      type: Number,
      default: 200
    }
  },
  data() {
    return {
      isDrawing: false,
      lastX: 0,
      lastY: 0,
      hasSignature: false,
      signatureImage: '',
      previewVisible: false,
      signatorInfo: null
    }
  },
  mounted() {
    this.initCanvas()
    this.loadSignatoryInfo()
  },
  methods: {
    initCanvas() {
      const canvas = this.$refs.signatureCanvas
      const ctx = canvas.getContext('2d')
      ctx.strokeStyle = '#000'
      ctx.lineWidth = 2
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
    },
    async loadSignatoryInfo() {
      if (!this.signatoryId) return
      try {
        const res = await getSignatoryDetail(this.signatoryId)
        if (res.code === 200) {
          this.signatorInfo = res.data
          // 如果已有签名，加载签名图片
          if (res.data.imageUrl) {
            this.loadExistingSignature(res.data.imageUrl)
          }
        }
      } catch (error) {
        console.error('加载签名人信息失败', error)
      }
    },
    loadExistingSignature(imageUrl) {
      const canvas = this.$refs.signatureCanvas
      const ctx = canvas.getContext('2d')
      const img = new Image()
      img.onload = () => {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        this.hasSignature = true
        this.signatureImage = canvas.toDataURL('image/png')
      }
      img.src = imageUrl
    },
    startDrawing(e) {
      const canvas = this.$refs.signatureCanvas
      this.isDrawing = true
      const rect = canvas.getBoundingClientRect()
      
      if (e.type === 'mousedown') {
        this.lastX = e.clientX - rect.left
        this.lastY = e.clientY - rect.top
      }
    },
    draw(e) {
      if (!this.isDrawing) return
      
      const canvas = this.$refs.signatureCanvas
      const ctx = canvas.getContext('2d')
      const rect = canvas.getBoundingClientRect()
      
      let currentX, currentY
      
      if (e.type === 'mousemove') {
        currentX = e.clientX - rect.left
        currentY = e.clientY - rect.top
      }
      
      ctx.beginPath()
      ctx.moveTo(this.lastX, this.lastY)
      ctx.lineTo(currentX, currentY)
      ctx.stroke()
      
      this.lastX = currentX
      this.lastY = currentY
      this.hasSignature = true
    },
    endDrawing() {
      this.isDrawing = false
      if (this.hasSignature) {
        this.signatureImage = this.$refs.signatureCanvas.toDataURL('image/png')
      }
    },
    handleTouchStart(e) {
      e.preventDefault()
      const touch = e.touches[0]
      const mouseEvent = new MouseEvent('mousedown', {
        clientX: touch.clientX,
        clientY: touch.clientY
      })
      this.$refs.signatureCanvas.dispatchEvent(mouseEvent)
    },
    handleTouchMove(e) {
      e.preventDefault()
      const touch = e.touches[0]
      const mouseEvent = new MouseEvent('mousemove', {
        clientX: touch.clientX,
        clientY: touch.clientY
      })
      this.$refs.signatureCanvas.dispatchEvent(mouseEvent)
    },
    handleTouchEnd(e) {
      e.preventDefault()
      const mouseEvent = new MouseEvent('mouseup', {})
      this.$refs.signatureCanvas.dispatchEvent(mouseEvent)
    },
    clearSignature() {
      const canvas = this.$refs.signatureCanvas
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      this.hasSignature = false
      this.signatureImage = ''
    },
    async saveSignature() {
      if (!this.hasSignature) {
        this.$message.warning('请先进行签名')
        return
      }
      
      try {
        // 将签名图片保存到签名人信息中
        const res = await saveSignatory({
          id: this.signatoryId,
          imageUrl: this.signatureImage,
          signatureType: 'digital'
        })
        
        if (res.code === 200) {
          this.$message.success('签名保存成功')
          this.$emit('signature-saved', this.signatureImage)
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存签名失败', error)
        this.$message.error('保存签名失败')
      }
    },
    previewSignature() {
      if (!this.hasSignature) {
        this.$message.warning('请先进行签名')
        return
      }
      this.previewVisible = true
    },
    downloadSignature() {
      if (!this.signatureImage) return
      
      const link = document.createElement('a')
      link.download = `signature_${this.signatoryId}_${new Date().getTime()}.png`
      link.href = this.signatureImage
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 给外部使用的方法
    getSignatureData() {
      return this.signatureImage
    }
  }
}
</script>

<style lang="scss" scoped>
.digital-signature {
  .signature-card {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 20px;
    background-color: #fff;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      h3 {
        margin: 0;
        font-size: 16px;
      }
    }
    
    .signature-container {
      margin-bottom: 15px;
      
      .signature-canvas {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        cursor: crosshair;
        background-color: #fff;
      }
      
      .signature-tip {
        margin-top: 5px;
        font-size: 12px;
        color: #909399;
        text-align: center;
      }
    }
    
    .signature-info {
      margin-bottom: 15px;
      
      p {
        margin: 5px 0;
        font-size: 14px;
      }
    }
    
    .signature-actions {
      display: flex;
      justify-content: center;
      gap: 10px;
    }
  }
  
  .preview-content {
    display: flex;
    justify-content: center;
    
    .preview-image {
      max-width: 100%;
      border: 1px solid #ebeef5;
    }
    
    .no-signature {
      color: #909399;
      padding: 20px;
    }
  }
}
</style> 